<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="价格名称" prop="priceName">
        <el-input
          v-model="queryParams.priceName"
          placeholder="请输入价格名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="用水性质" prop="waterType">
        <el-select v-model="queryParams.waterType" placeholder="用水性质" clearable>
          <el-option
            v-for="dict in dict.type.water_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="启用状态" prop="isUsed">
        <el-select v-model="queryParams.isUsed" placeholder="启用状态" clearable>
          <el-option
            v-for="dict in dict.type.price_is_used"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['revenue:priceConfig:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['revenue:priceConfig:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['revenue:priceConfig:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['revenue:priceConfig:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="priceConfigList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" v-if="false"/>
      <el-table-column label="价格编号" align="center" prop="priceCode" width="120"/>
      <el-table-column label="价格名称" align="center" prop="priceName" />
<!--      <el-table-column label="用水性质" align="center" prop="waterType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.water_type" :value="scope.row.waterType"/>
        </template>
      </el-table-column>-->
      <el-table-column label="启用状态" align="center" prop="isUsed">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.price_is_used" :value="scope.row.isUsed"/>
        </template>
      </el-table-column>
      <el-table-column label="阶梯类型" align="center" prop="ladderType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ladder_type" :value="scope.row.ladderType"/>
        </template>
      </el-table-column>
      <el-table-column label="基本水价" align="center" prop="basePrice">
        <template slot-scope="scope">
          <span v-if="scope.row.ladderType === 1">
            {{ scope.row.price1 }}元 (0-{{ scope.row.waterCons1 }}m³)<br/>
            {{ scope.row.price2 }}元 ({{ parseInt(scope.row.waterCons1)+1 }}-{{ scope.row.waterCons2 }}m³)<br/>
            {{ scope.row.price3 }}元 ({{ parseInt(scope.row.waterCons2)+1 }}m³以上)
          </span>
          <span v-else>{{ scope.row.price1 }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="污水处理费" align="center" prop="sewageFee">
        <template slot-scope="scope">{{ scope.row.sewageFee }}元</template>
      </el-table-column>
      <el-table-column label="不征税自来水" align="center" prop="noTax">
        <template slot-scope="scope">{{ scope.row.noTax }}元</template>
      </el-table-column>
      <el-table-column label="综合水价" align="center" prop="totalPrice">
        <template slot-scope="scope">
          <span v-if="scope.row.ladderType === 1">
            {{ (parseFloat(scope.row.price1) + parseFloat(scope.row.sewageFee) + parseFloat(scope.row.noTax)).toFixed(2) }}元<br/>
            {{ (parseFloat(scope.row.price2) + parseFloat(scope.row.sewageFee) + parseFloat(scope.row.noTax)).toFixed(2) }}元<br/>
            {{ (parseFloat(scope.row.price3) + parseFloat(scope.row.sewageFee) + parseFloat(scope.row.noTax)).toFixed(2) }}元
          </span>
          <span v-else>{{ (parseFloat(scope.row.price1) + parseFloat(scope.row.sewageFee) + parseFloat(scope.row.noTax)).toFixed(2) }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="阶梯开始时间" align="center" prop="periodStartDate" width="120">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.periodStartDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['revenue:priceConfig:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['revenue:priceConfig:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改价格设置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="价格名称" prop="priceName">
          <el-input v-model="form.priceName" placeholder="请输入价格名称" />
        </el-form-item>
<!--        <el-form-item label="用水性质" prop="waterType" v-if="false">
          <el-select v-model="form.waterType" placeholder="用水性质" @change="handleWaterTypeChange">
            <el-option
              v-for="dict in dict.type.water_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>-->
        <el-form-item label="启用状态" prop="isUsed">
          <el-select v-model="form.isUsed" placeholder="启用状态">
            <el-option
              v-for="dict in dict.type.price_is_used"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="阶梯类型" prop="ladderType">
          <el-select v-model="form.ladderType" placeholder="阶梯类型" @change="handleLadderTypeChange">
            <el-option
              v-for="dict in dict.type.ladder_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>

        <div v-if="form.ladderType === 1">
          <el-divider content-position="left">阶梯一</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="阶梯水量1(m³)" prop="waterCons1">
                <el-input v-model="form.waterCons1" placeholder="请输入阶梯水量1" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="阶梯价格1(元)" prop="price1">
                <el-input v-model="form.price1" placeholder="请输入阶梯价格1" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">阶梯二</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="阶梯水量2(m³)" prop="waterCons2">
                <el-input v-model="form.waterCons2" placeholder="请输入阶梯水量2" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="阶梯价格2(元)" prop="price2">
                <el-input v-model="form.price2" placeholder="请输入阶梯价格2" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">阶梯三</el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="阶梯价格3(元)" prop="price3">
                <el-input v-model="form.price3" placeholder="请输入阶梯价格3" />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div v-else>
          <el-form-item label="基本水价(元)" prop="price1">
            <el-input v-model="form.price1" placeholder="请输入基本水价" />
          </el-form-item>
        </div>

        <el-divider content-position="left">附加费用</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="污水处理费(元)" prop="sewageFee">
              <el-input v-model="form.sewageFee" placeholder="请输入污水处理费" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="不征税自来水(元)" prop="noTax">
              <el-input v-model="form.noTax" placeholder="请输入不征税自来水" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="left">综合水价预览</el-divider>
        <el-alert
          v-if="form.ladderType === 1 && form.price1 && form.sewageFee && form.noTax"
          :title="`阶梯一: ${(parseFloat(form.price1) + parseFloat(form.sewageFee) + parseFloat(form.noTax)).toFixed(2)}元 | 阶梯二: ${(parseFloat(form.price2) + parseFloat(form.sewageFee) + parseFloat(form.noTax)).toFixed(2)}元 | 阶梯三: ${(parseFloat(form.price3) + parseFloat(form.sewageFee) + parseFloat(form.noTax)).toFixed(2)}元`"
          type="info"
          :closable="false"
        />
        <el-alert
          v-else-if="form.price1 && form.sewageFee && form.noTax"
          :title="`综合水价: ${(parseFloat(form.price1) + parseFloat(form.sewageFee) + parseFloat(form.noTax)).toFixed(2)}元`"
          type="info"
          :closable="false"
        />
        <el-alert
          v-else
          title="请填写完整的水价信息以预览综合水价"
          type="warning"
          :closable="false"
        />

        <el-form-item label="阶梯开始时间" prop="periodStartDate">
          <el-date-picker clearable
                          v-model="form.periodStartDate"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择阶梯开始时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPriceConfig, getPriceConfig, delPriceConfig, addPriceConfig, updatePriceConfig } from "@/api/revenue/priceConfig";

export default {
  name: "PriceConfig",
  dicts: ['price_is_used', 'water_type', 'ladder_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 价格设置表格数据
      priceConfigList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        priceName: null,
        waterType: null,
        isUsed: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        priceName: [
          { required: true, message: "价格名称不能为空", trigger: "blur" }
        ],
        /*waterType: [
          { required: true, message: "用水性质不能为空", trigger: "change" }
        ],*/
        isUsed: [
          { required: true, message: "启用状态不能为空", trigger: "change" }
        ],
        ladderType: [
          { required: true, message: "阶梯类型不能为空", trigger: "change" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询价格设置列表 */
    getList() {
      this.loading = true;
      listPriceConfig(this.queryParams).then(response => {
        this.priceConfigList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        priceCode: null,
        priceName: null,
        waterType: null,
        isUsed: null,
        ladderType: null,
        price1: null,
        price2: null,
        price3: null,
        waterCons1: null,
        waterCons2: null,
        sewageFee: null,
        noTax: null,
        periodStartDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加价格设置";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getPriceConfig(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改价格设置";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updatePriceConfig(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addPriceConfig(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除价格设置编号为"' + ids + '"的数据项？').then(function() {
        return delPriceConfig(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('revenue/priceConfig/export', {
        ...this.queryParams
      }, `priceConfig_${new Date().getTime()}.xlsx`)
    },
    // 用水性质变化处理
    handleWaterTypeChange(value) {
      // 根据用水性质自动设置阶梯类型和默认费用
      if (value === '1') { // 居民生活用水
        this.form.ladderType = '1'; // 阶梯式
        this.form.sewageFee = '0.95';
        this.form.noTax = '0.35';
      } else if (value === '2') { // 非居民用水
        this.form.ladderType = '0'; // 非阶梯式
        this.form.sewageFee = '1.40';
        this.form.noTax = '0.40';
      } else if (value === '3') { // 特种用水
        this.form.ladderType = '0'; // 非阶梯式
        this.form.sewageFee = '1.40';
        this.form.noTax = '2.00';
      }
    },
    // 阶梯类型变化处理
    handleLadderTypeChange(value) {
      if (value === '0') {
        // 非阶梯式，清空阶梯2和阶梯3的数据
        this.form.price2 = null;
        this.form.price3 = null;
        this.form.waterCons1 = null;
        this.form.waterCons2 = null;
      }
    }
  }
};
</script>

<style scoped>
.el-divider__text {
  background-color: #f5f7fa;
}
</style>
